package com.spontaneappnew.activities;

import java.util.ArrayList;

import android.app.Activity;
import android.app.ProgressDialog;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.widget.ImageView;

import com.parse.ParseException;
import com.spontaneappnew.ImageUtils;
import com.spontaneappnew.Place;
import com.spontaneappnew.Places;
import com.spontaneappnew.R;
import com.spontaneappnew.adapters.PlacePicturesAdapter;
import com.viewpagerindicator.CirclePageIndicator;

public class ImageGalleryActivity extends Activity {

	private ViewPager ImageGalleryViewPager;
	private ArrayList<ImageView> ImagesArray;
	private PlacePicturesAdapter ImagesAdapter;
	private CirclePageIndicator CircleIndicator;
	private Place currentPlace;
	private int state;
	private ProgressDialog mProgressDialog;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_image_gallery);
		ImagesArray = new ArrayList<ImageView>();
		mProgressDialog = new ProgressDialog(this);
		currentPlace = Places.getInstance().getCurrentPlace();
		state = currentPlace.getNumOfImages();
		mProgressDialog.setMessage("Loading");
    	mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
    	mProgressDialog.setIndeterminate(true);
    	mProgressDialog.show();
		ImageGalleryViewPager = (ViewPager) findViewById(R.id.image_gallery_view_pager);
		CircleIndicator = (CirclePageIndicator) findViewById(R.id.image_gallery_titles);
		for (int i=0;i<currentPlace.getImagesArray().size();i++){
			new loadImagesAsyncTask().execute(new int[]{i});
		}
		
	}
	
	private class loadImagesAsyncTask extends AsyncTask<int[], Void, byte[]>{

		private int x;
		
		@Override
		protected byte[] doInBackground(int[]... params) {
			this.x = params[0][0];
			try {
				return currentPlace.getImagesArray().get(x).getData();
			} catch (ParseException e) {
				e.printStackTrace();
			}
			return null;
		}
		
		@Override
		protected void onPostExecute(byte[] result) {
			super.onPostExecute(result);
			ImageView img = new ImageView(ImageGalleryActivity.this);
			img.setPadding(8, 0, 8, 0);
			Bitmap RoundedImage = new ImageUtils().getRoundedRectBitmap(BitmapFactory.decodeByteArray(result, 0, result.length), 20);
			img.setImageBitmap(RoundedImage);
			ImagesArray.add(img);
			state--;
			if (state==0)
				setAdapter();
		}
	}
	
	private void setAdapter(){
		ImagesAdapter = new PlacePicturesAdapter(ImageGalleryActivity.this,ImagesArray,false);
		ImageGalleryViewPager.setAdapter(ImagesAdapter);
		CircleIndicator.setViewPager(ImageGalleryViewPager);
		int CurrentItem  = getIntent().getIntExtra("CurrentImage", 0);
		ImageGalleryViewPager.setCurrentItem(CurrentItem);
		mProgressDialog.hide();
	}
		
}
